package com.cyx.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.catalina.User;
import org.apache.shiro.mgt.AuthorizingSecurityManager;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.mgt.WebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") SecurityManager securityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(securityManager);

        /**  常用过滤器：
         *      anon:无需认证即可访问
         *      authc:要授权才可访问
         *      user:如果使用rememberMe的功能可以直接访问
         *      perms:该资源必须得到资源授权才可以访问
         *      roles:该资源必须得到角色授权才可以访问
         */
        Map<String,String> filterChainDefinitionMap = new LinkedHashMap<>();
        //拦截
        filterChainDefinitionMap.put("/","anon");
        filterChainDefinitionMap.put("/user","anon");
        filterChainDefinitionMap.put("/user/*","authc");
        filterChainDefinitionMap.put("/order","authc");
        //权限校验拦截
        filterChainDefinitionMap.put("/order/add","perms[order:add]");
        filterChainDefinitionMap.put("/order/update","perms[order:add]");

        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        //配置自定义登录页面
        bean.setLoginUrl("/login");
        return bean;
    }

    @Bean(name = "securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManager(UserRealm userRealm){
        return new DefaultWebSecurityManager(userRealm);
    }

    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }


    @Bean(name = "shiroDialect")
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();

    }
}
